<?php
(!defined('IN_SYSTEM') || !defined('ADMIN_PRE')) && exit('Access Denied!');
$f = isset($_REQUEST['f'])?$_REQUEST['f']:'index';
if(isset($_G['usergroup']['access']["cat$f"]) && !ican("cat$f")){
	msg('没有权限');
}
$t = intval($_REQUEST['t']);
$class=array(
	0=>array('name'=>'文章分类','table'=>'article','referid'=>'aid'),
	1=>array('name'=>'商品分类','table'=>'product','referid'=>'pid'),
	2=>array('name'=>'品牌分类','table'=>'product','referid'=>'pid'),
	3=>array('name'=>'分类A','table'=>'','referid'=>''),
	4=>array('name'=>'分类B','table'=>'','referid'=>''),
	5=>array('name'=>'分类C','table'=>'','referid'=>''),
	6=>array('name'=>'分类D','table'=>'','referid'=>''),
	7=>array('name'=>'分类E','table'=>'','referid'=>''),
	8=>array('name'=>'分类F','table'=>'','referid'=>'')
);
if ($f == 'index') {
	$sql = "SELECT * FROM ".DB_PREFIX."category WHERE type={$t} AND pid=0 ORDER BY listorder";
	$result = $_G['db']->fetch_all($sql);
	
	include admintemplate('category');

} elseif ($f == 'add') {
	$sql = "SELECT * FROM ".DB_PREFIX."category WHERE type={$t} ORDER BY listorder";
	$cates = $_G['db']->fetch_all($sql);
	$pid=getGP('pid','G','int');
	$listorder = $_G['db']->result("SELECT MAX(listorder) FROM ".DB_PREFIX."category  WHERE type='".$t."' limit 1");
	$result = array('savetype'=>'new','cid' =>null,'listorder'=>++$listorder, 'catename'=>null,'urlname'=>null,'keywords'=>null,'description'=>null,'redirect'=>null,'status'=>null);
	include admintemplate('category');

} elseif ($f == 'edit') {
	$id = getGP('id','G','int');
	$sql = "SELECT * FROM ".DB_PREFIX."category WHERE type={$t} AND cid!={$id} ORDER BY listorder";
	$cates = $_G['db']->fetch_all($sql);
	$result = $_G['db']->fetch_one_array("SELECT * FROM ".DB_PREFIX."category WHERE cid = $id");
	$result['savetype'] = 'edit';
	include admintemplate('category');

} elseif ($f == 'save') {
	if(!ican('catedit')){
		msg('没有权限');
	}
	$savetype = getGP('savetype','P');
	$cateid = getGP('id','P','int');
	$category = array();
	$category['catename'] = check_str(getGP('catename','P'));
	$category['keywords'] = check_str(getGP('keywords','P'));
	$category['description'] = check_str(getGP('description','P'));
	$category['urlname'] = getGP('urlname','P');
	$category['urlname'] = preg_match('/^[a-z0-9\-\_]*[a-z\-_]+[a-z0-9\-\_]*$/i', $category['urlname']) ? $category['urlname'] : '';
	$category['redirect'] = getGP('redirect','P');
	$category['status'] = getGP('status','P') ? 1 : 0;
	$category['type'] = getGP('type','P','int');
	$category['pid'] = getGP('cparent','P','int');
	$category['access'] = getGP('access','P','int');
	$category['listorder'] = getGP('listorder','P');
	
	if ($savetype == 'new') {
		if(!ican('catadd')){
			msg('没有权限');
		}
		
		$id=$_G['db']->insert('category', $category);
		recache('category');	//更新缓存
		save_alias($category['urlname'],$id,'category');
		msg('成功添加分类','?m=category');
	} elseif ($savetype == 'edit') {
		$_G['db']->update('category', $category, array('cid'=>$cateid));
		recache('category');	//更新缓存
		save_alias($category['urlname'],$cateid,'category');
		msg('修改成功');
	}

} elseif ($f == 'save_order') {
	if(!ican('catedit') && !ican('catadd')){
		msg('没有权限');
	}
	$order = getGP('order','P','array');
	foreach ($order as $key => $val) {
		$values.=$dot."($key,'$val')";
		$dot=",";
//		if($t==1) {
//			$count = $_G['db']->result("SELECT COUNT(*) AS num FROM ".DB_PREFIX."link WHERE `visible` =1 AND cid = '$key'");
//		}elseif($t==2){
//			$count = $_G['db']->result("SELECT COUNT(*) AS num FROM ".DB_PREFIX."product WHERE `status` < 4 AND cid = '$key'");
//		}else{
//			$count = $_G['db']->result("SELECT COUNT(*) AS num FROM ".DB_PREFIX."article WHERE `status` < 4 AND cid = '$key'");
//		}
//		$_G['db']->query("UPDATE ".DB_PREFIX."category SET `total` = '$count', listorder = '$val' WHERE cid = '$key'");
	}
	$_G['db']->query("REPLACE INTO".table('category')."(cid,listorder) values  $values;");
	recache('category');	//更新缓存
	msg("成功更新排序");

} elseif ($f == 'del') {
	$id = getGP('id','G','int');
	$type = $_G['db']->result("SELECT type FROM ".DB_PREFIX."category WHERE cid = '$id'");
	
	$table=$class[$type]['table'];
	$referid=$class[$type]['referid'];
	if(!$table || !$referid)msg("参数错误");
	$query = $_G['db']->query("SELECT {$referid} FROM".table($table)."WHERE cid = '$id'");
	while ($row = $_G['db']->fetch_array($query)) {
		$ids[]=$row[$referid];
	}
	if(!empty($ids)){
		$in=implode(',',$ids);
		$_G['db']->query("DELETE FROM".table('comment')."WHERE referid IN($in) AND type = '$type'");	//删除评论
		//删除附件
		$query = $_G['db']->query("SELECT filepath,thumb FROM ".DB_PREFIX."files WHERE referid IN($in) AND type = '$type'");
		while($file=$_G['db']->fetch_array($query)){
			@unlink(BASE_ROOT.$file['filepath']);
			if ( !empty($file['thumb']) ) {
				@unlink(BASE_ROOT.$file['thumb']);
			}
		}
		$_G['db']->query("DELETE FROM".table('files')."WHERE referid IN($in)  AND type = '$type'");
	}
	$_G['db']->query("DELETE FROM".table($table)."WHERE cid = '$id'");
	$_G['db']->query("DELETE FROM".table('category')."WHERE cid = '$id'");
	//循环删除子级
	deletechild(array($id));
	recache('category');	//更新缓存
	msg('删除成功');

} elseif ( $f == 'merge' ) {
	
	$idarr = getGP('id','P','array');
	$tocid = getGP('tocid','P','int');
	if ( empty($idarr) ) msg('请选择要合并的分类。');
	if ( !$tocid ) msg('请选择目标分类。');
	$idarr = array_unique($idarr);
	$idstr = implode(',', $idarr);
	if ( !preg_match('/^[0-9,]+$/', $idstr) ) msg('非法的ID参数。');
	$type = $_G['db']->result("SELECT type FROM".table('category')."WHERE cid = '$tocid'");
	$table=$class[$type]['table'];
	$referid=$class[$type]['referid'];
	if(!$table || !$referid)msg("参数错误");
	
	if ( $_G['db']->result("SELECT cid FROM ".DB_PREFIX."category WHERE cid = '$tocid'") ) {
		$_G['db']->query("UPDATE ".DB_PREFIX."{$table} SET cid = '$tocid' WHERE cid IN ($idstr) AND cid <> '$tocid' ");
		$_G['db']->query("DELETE FROM ".DB_PREFIX."category WHERE cid IN ($idstr) AND cid <> '$tocid' ");
		recache('category');
	}
	msg('成功合并分类');
}elseif ( $f=='child'){
	$id=getGP('id','G','int');
	$data['s']=false;
	if($id){
		$sql="SELECT * FROM".table('category')."WHERE pid=".$id;
		$data['d']=$_G['db']->fetch_all($sql);
		if(!empty($data['d']))$data['s']=true;
	}
	echo json_encode($data);exit;
}

function deletechild($ids){
		if(empty($ids))return;
		global $_G;
		while(true){
			$sub =  $_G['db']->fetch_all("SELECT cid FROM".table("category")."WHERE pid IN(".implode(',',$ids).")");
			$_G['db']->query("DELETE  FROM".table('category')." WHERE pid IN(".implode(',', $ids).") ");
			if(!empty($sub)){
				$ids=array();
				foreach($sub as $v){
					$ids[$v['cid']]=$v['cid'];
				}
			}else{
				break;
			}
			
		}
		
	}
?>